package com.linkgie.galaxyframework.utils.json;

import java.io.IOException;
import java.lang.reflect.Proxy;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

public class ProxyDeserializer<T> extends StdDeserializer<T> {

	private static final long serialVersionUID = 2563258794464565804L;

	private ObjectMapper context;

	private Class<?> valueType;

	protected ProxyDeserializer(Class<?> valueType, ObjectMapper context) {
		super(valueType);
		this.valueType = valueType;
		this.context = context;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
		JsonNode jsonValue = p.readValueAsTree();

		ClassLoader classloader = Thread.currentThread().getContextClassLoader();
		if (classloader == null) {
			classloader = valueType.getClassLoader();
		}
		return (T) Proxy.newProxyInstance(classloader, new Class<?>[] { valueType, JsonProxy.class },
				new JsonProxyAccesser(jsonValue, context));
	}

}
